package com.heh.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heh.mybatisplus.mapper.UserAccountMapper;
import com.heh.mybatisplus.model.Result;
import com.heh.mybatisplus.model.UserAccount;
import com.heh.mybatisplus.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @项目名： spring-emq
 * @包名： com.heh.mybatisplus.service.impl
 * @文件名: UserAccountServiceImpl
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/14 14:14
 * @描述：
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {
    @Autowired
    private ObjectMapper objectMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> transferAccounts(Long fromId, Long toId, BigDecimal amount) throws JsonProcessingException {
        if (fromId == toId) {
            log.info("账户不能都一样");
            return Result.fail(400, "账户不能都一样");
        }
        UserAccount fromUserAccount = baseMapper.selectById(fromId);
        UserAccount toUserAccount = baseMapper.selectById(toId);
        if (fromUserAccount == null || toUserAccount == null) {
            log.info("账户为空");
            return Result.fail(400, "账户为空");
        }
        log.info("fromUserAccount.getBalance1(){}", fromUserAccount.getBalance().compareTo(amount));
        if (fromUserAccount.getBalance().compareTo(amount) < 0) {
            log.info("余额不足");
            return Result.fail(400, "余额不足");
        }
        BigDecimal subtractBigDecimal = fromUserAccount.getBalance().subtract(amount);
        BigDecimal addBigDecimal = toUserAccount.getBalance().add(amount);
        log.info("fromUserAccount.getBalance2(){}", subtractBigDecimal);
        log.info("toUserAccount.getBalance3(){}", addBigDecimal);
        fromUserAccount.setBalance(subtractBigDecimal);
        toUserAccount.setBalance(addBigDecimal);

        log.info("objectMapper1{}", objectMapper.writeValueAsString(fromUserAccount));
        log.info("objectMapper2{}", objectMapper.writeValueAsString(toUserAccount));
        int i = baseMapper.updateById(fromUserAccount);
        int z = baseMapper.updateById(toUserAccount);
        if (i == 1 && z == 1) {
            String text = "转账成功";
            log.info("转账成功");
            return Result.success(true);
        }
        return Result.fail(400, "转账失败");
    }
}
